<?php
/**
 * @author all@cosmos-framework.org
 * @copyright (c) 2013 cosmos-framework.org
 * @license http://www.opensource.org/licenses/mit-license.php
 * @link http://cosmos-framework.org/
 * @package cosmos.framework
 * @version 2.0
 */
namespace Cosmos;

class Assert {

    /**
     * @param mixed $v
     * @param string $message
     * @param int $code
     * @return mixed
     */
    public static function full($v, $message = null, $code = 400) {

        return empty($v) ? self::_fail($message, $code) : $v;
    }

    /**
     * @param mixed $v
     * @param string $assert
     * @param string $message
     * @param int $code
     * @return mixed
     */
    public static function is($v, $assert, $message = null, $code = 400) {

        return eval('?><?php return ' . $assert . ';') ? $v : self::_fail($message, $code);
    }

    /**
     * @param mixed $v
     * @param string $message
     * @param int $code
     * @return mixed
     */
    public static function mail($v, $message = null, $code = 400) {

        return self::match($v, '/^(?:(?:(?:(?:[a-zA-Z0-9!#\$%&\'*+\-\/=?\^_`{|}~]+)(?:\.(?:[a-zA-Z0-9!#\$%&\'*+\-\/=?\^_`{|}~]+))*)|(?:"(?:\\[^\r\n]|[^\\"])*")))\@(?:(?:(?:(?:[a-zA-Z0-9!#\$%&\'*+\-\/=?\^_`{|}~]+)(?:\.(?:[a-zA-Z0-9!#\$%&\'*+\-\/=?\^_`{|}~]+))*)|(?:\[(?:\\\S|[\x21-\x5a\x5e-\x7e])*\])))$/', $message, $code);
    }

    /**
     * @param mixed $v
     * @param string $pttr
     * @param string $message
     * @param int $code
     * @return mixed
     */
    public static function match($v, $pttr, $message = null, $code = 400) {

        return preg_match($pttr, $v) ? $v : self::_fail($message, $code);
    }

    /**
     * @param mixed $v
     * @param string $message
     * @param int $code
     * @return mixed
     */
    public static function url($v, $message = null, $code = 400) {

        return self::match($v, '/^https?:\/\/[a-zA-Z0-9;\/?:@&=+\$,\-_\.!~*\'()%]*$/', $message, $code);
    }

    /**
     * @param string $message
     * @param int $code
     */
    private static function _fail($message, $code) {

        throw new Exception($message, $code);
    }

}
